package com.github.shiqiyue.app.config.async;

import com.github.shiqiyue.app.common.trace.TraceTaskDecorator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/***
 * 异步配置
 * @author wenyao.wu
 * @date 2019/9/6
 */
@Slf4j
@EnableAsync(mode = AdviceMode.ASPECTJ)
@Component
public class AsyncConfiguration {

    /**
     * 自定义异步线程池
     *
     * @return
     */
    @Bean
    public AsyncTaskExecutor taskExecutor() {
        TaskDecorator taskDecorator = new TraceTaskDecorator();
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("async-executor");
        executor.setTaskDecorator(taskDecorator);
        executor.setMaxPoolSize(10);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }


}
